package top.chenfu.boot.auth.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.chenfu.boot.auth.dao.UserMapper;
import top.chenfu.boot.auth.model.User;
import top.chenfu.boot.auth.util.UserStatusEnum;
import top.chenfu.boot.auth.vo.UserVo;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Service
@Slf4j
public class UserServiceImpl {

    @Autowired
    private UserMapper userMapper;

    public User getUser(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    public Integer add(User user) {
        return userMapper.insertSelective(user);
    }

    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    public Integer update(User user, boolean isPatch) {
        try {
            User oldUser = userMapper.selectByPrimaryKey(user);
            if (Objects.isNull(oldUser)) {
                return 0;
            }
            user.setId(oldUser.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        if (isPatch) {
            return userMapper.updateByPrimaryKeySelective(user);
        }
        return userMapper.updateByPrimaryKey(user);
    }

    public Integer delete(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        if (Objects.isNull(user) || user.getDeleteFlag() || user.getIsEnable()) {
            return 0;
        }
        user.setDeleteFlag(UserStatusEnum.IS_DELETE.isStatus());
        return userMapper.updateByPrimaryKeySelective(user);
    }

    public String login(UserVo userVo, HttpSession session) {
        User user = userMapper.login(userVo.getUserName(), userVo.getPassword());
        if (Objects.isNull(user)) {
            return null;
        }
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        log.info("sessionId:{}", session.getId());
        BeanUtils.copyProperties(user, userVo);
        userVo.setPassword(null);
        session.setAttribute(token, userVo);
        return token;
    }

}
